﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using ElectronicCommerce.Framework.Web.UI.GeneratedImage.ImageStore;
using ElectronicCommerce.Framework.Web.UI.GeneratedImage.ImageTransform;

namespace ElectronicCommerce.Framework.Web.UI.GeneratedImage
{
    public class ImageGenerator
    {
        public ImageGenerator()
        {
            ContentType = ImageFormat.Jpeg;
            ImageTransforms = new List<ImageTransform.ImageTransform>();
        }

        /// <summary>
        /// 图片类型
        /// </summary>
        public ImageFormat ContentType { get; set; }

        /// <summary>
        /// 图片存储
        /// </summary>
        private IImageStore ImageStore
        {
            get
            {
                return DiskImageStore.Instance;
            }
        }

        /// <summary>
        /// 图片转换器
        /// </summary>
        public List<ImageTransform.ImageTransform> ImageTransforms
        {
            get;
            private set;
        }

        /// <summary>
        /// 获取图片类型
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        internal static string GetImageMimeType(ImageFormat format)
        {
            string mimeType = "image/x-unknown";

            if (format.Equals(ImageFormat.Gif))
            {
                mimeType = "image/gif";
            }
            else if (format.Equals(ImageFormat.Jpeg))
            {
                mimeType = "image/jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                mimeType = "image/png";
            }
            else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp))
            {
                mimeType = "image/bmp";
            }
            else if (format.Equals(ImageFormat.Tiff))
            {
                mimeType = "image/tiff";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                mimeType = "image/x-icon";
            }

            return mimeType;
        }

        /// <summary>
        /// 集成图片
        /// </summary>
        /// <param name="request"></param>
        public void Process(ImageGenerateRequest request)
        {
            if (!request.IsRequestOriginalImage)
            {
                // 设置缩略图转换属性
                ImageResizeTransform imageResizeTransform = new ImageResizeTransform();
                imageResizeTransform.Width = request.FactWidth;
                imageResizeTransform.Height = request.FactHeight;
                imageResizeTransform.Mode = request.ResizeMode;

                ImageTransforms.Clear();
                ImageTransforms.Add(imageResizeTransform);

                using (Image image = Image.FromFile(request.ImagePath))
                {
                    ImageInfo imageMethodData = new ImageInfo(image);

                    MemoryStream imageOutputBuffer = new MemoryStream();

                    Debug.Assert(!(imageMethodData.Image == null && imageMethodData.ImageByteBuffer == null));
                    if (imageMethodData.Image != null)
                    {
                        RenderImage(GetImageThroughTransforms(imageMethodData.Image), imageOutputBuffer);
                    }
                    else if (imageMethodData.ImageByteBuffer != null)
                    {
                        RenderImage(GetImageThroughTransforms(imageMethodData.ImageByteBuffer), imageOutputBuffer);
                    }

                    byte[] buffer = imageOutputBuffer.GetBuffer();

                    ImageStore.Add(request.ThumbnailImagePath, buffer);
                }
            }
            else
            {
                if (request.ImagePath != request.ThumbnailImagePath)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(request.ThumbnailImagePath)))
                        Directory.CreateDirectory(Path.GetDirectoryName(request.ThumbnailImagePath));

                    File.Copy(request.ImagePath, request.ThumbnailImagePath);
                }
            }
        }

        public bool BuildFixedImage(string path, Size size)
        {
            ImageResizeTransform imageResizeTransform = new ImageResizeTransform();
            try
            {
                FileInfo info = new FileInfo(path);
                Image newImage = imageResizeTransform.BuildImage(path, size);
                if (info.Exists)
                    info.Delete();
                newImage.Save(path);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 执行图片转换
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private Image GetImageThroughTransforms(Image image)
        {
            Image temp = image;

            foreach (var tran in ImageTransforms)
            {
                temp = tran.ProcessImage(temp);
            }
            return temp;
        }

        /// <summary>
        /// 执行图片转换
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private Image GetImageThroughTransforms(byte[] buffer)
        {
            MemoryStream memoryStream = new MemoryStream(buffer);
            return GetImageThroughTransforms(Image.FromStream(memoryStream));
        }

        /// <summary>
        /// 把图片保存在Stream中
        /// </summary>
        /// <param name="image"></param>
        /// <param name="outStream"></param>
        private void RenderImage(Image image, Stream outStream)
        {
            //MemoryStream memoryStream = new MemoryStream();

            //image.Save(memoryStream, ContentType);
            //byte[] arr = memoryStream.GetBuffer();
            //outStream.Write(arr, 0, arr.Length);
            image.Save(outStream, ContentType);
        }
    }
}
